package com.pankajm.common;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Files {
	public static List<String> readLines(String dirPath, String filename) throws IOException {
		List<String> lines = new ArrayList<String>();
		File file = openFile(dirPath + System.getProperty("file.separator") + filename);
		FileReader fileReader = new FileReader(file);
		BufferedReader br = new BufferedReader(fileReader);
		String line = null;
		
		while ((line = br.readLine()) != null) {
			lines.add(line);
		}
		
		br.close();
 		return lines;
	}
	
	public static void writeLines(List<String> lines, String dirPath, String filename) throws IOException {
		String pathname = dirPath + System.getProperty("file.separator") + filename;
		File file = createOrOpenFile(pathname);
		
		FileWriter fileWriter = new FileWriter(file);
		BufferedWriter bw = new BufferedWriter(fileWriter);
		
		for (String line : lines) {
			bw.append(line);
			bw.append("\n");
		}
		
		bw.close();
	}
	
	private static File createOrOpenFile(String pathname) throws IOException {
		File file = new File(pathname);
		if (!file.exists()) {
			file.createNewFile();
		}
		return file;
	}
	
	private static File openFile(String pathname) throws IOException {
		File file = new File(pathname);
		if (file.canRead()) {
			return file;
		} else {
			throw new IOException("Can't open File [" + file.getAbsolutePath() + "]");
		}
	}
}
